package com.coinworld.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

public class HttpAsyncUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpAsyncUtils.class);
    private static CloseableHttpAsyncClient httpAsyncClient = null;

    static {
        try {
            logger.info("===========开始构建http异步连接池================");
            ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
            PoolingNHttpClientConnectionManager pool = new PoolingNHttpClientConnectionManager(ioReactor);
            pool.setMaxTotal(2000);              //设置最多连接数
            pool.setDefaultMaxPerRoute(1000);     //设置每个host最多50个连接数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(5000)         //设置请求响应超时时间
                    .setConnectTimeout(5000)        //设置请求连接超时时间
                    .build();
            httpAsyncClient = HttpAsyncClients.custom()
                    .setConnectionManager(pool)                //设置连接池
                    .setDefaultRequestConfig(requestConfig)    //设置请求配置
                    .build();
        } catch (IOReactorException e) {
            logger.error("============构建异步连接池失败============={}", e);
        }
        httpAsyncClient.start();                                //启动异步连接
        logger.info("===========http异步连接池创建成功================");
    }

    public static void send(String url, Map<String, String> map, String encoding) {

        try {
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            //装填参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (map != null) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //设置参数到请求对象中
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            final Future future = httpAsyncClient.execute(httpPost, null);
            HttpResponse response = (HttpResponse) future.get();
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                String body = EntityUtils.toString(entity, encoding);
                logger.info(map.get("Mobile") + "send sms response result:{}",body);
            }
            EntityUtils.consume(entity);
        }catch (Exception e) {
            logger.error(map.get("Mobile")+"send sms error:{}",e);
            e.printStackTrace();
        }
    }

}
